<?php
/**
 * PublicAction
 * 注册、登陆等公共程序
 * Author: huqian
 * CreateDate: 2012-09-03
 */

class PublicAction extends CommonAction {
    /**
     * 验证码
     */
    public function authcode() {
        $type = isset($_GET['type']) ? $_GET['type'] : 'png';
        import("@.ORG.Image");
        Image::buildImageVerify(4, 5, $type);
    }

    /**
     * 校验验证码
     */
    function checkauth() {
        //因为验证码是表达式，在Image.class.php中没有经过md5加密
        $auth = $_POST['auth'];
        $auth_array = C('AUTH_ARRAY');
        $key = $_SESSION['verify'];
        if ($auth != $auth_array[$key]) {
            echo 1; //不正确
        } else {
            echo 2; //输入正确
        }
    }

    /**
     * 用户注册页面
     */
    function register() {
        if (isset($_SESSION[C('USER_AUTH_KEY')])) {
            //已登录跳转至首页
            $this->redirect('Index/index');
        } else {
            $this->assign('title', '用户注册 - ' . C('TITLE'));
            $this->display();
        }
    }

    /**
     * 用户注册，电子邮箱验证是否唯一
     * @param $user_email string 用户邮箱，未指定时post获取
     * @param $return_type int 返回类型，默认为1，echo输出，用于ajax调用；为2时，使用return 返回
     */
    function checkuseremail($user_email = '', $return_type = 1) {
        $user_email = $user_email ? $user_email : addslashes($_POST['user_email']);
        $User = M('user_base_info');
        $user_code = $User->where("user_email = '$user_email'")->getField('user_code');
        if ($user_code) {
            //已存在，不可使用
            if ($return_type == 1) {
                echo 1;
            } else {
                return 1;
            }
        } else {
            //邮箱可以使用
            if ($return_type == 1) {
                echo 2;
            } else {
                return 2;
            }
        }
    }

    /**
     * 用户注册，昵称验证是否唯一
     * @param $user_nickname string 用户昵称，未指定时post获取
     * @param $return_type int 返回类型，默认为1，echo输出，用于ajax调用；为2时，使用return 返回
     */
    function checknickname($user_nickname = '', $return_type = 1) {
        $user_nickname = $user_nickname ? $user_nickname : addslashes($_POST['user_nickname']);
        $User = M('user_base_info');
        $user_nickname = $User->where("user_nickname = $user_nickname")->getField('user_nickname');
        if ($user_nickname) {
            //已存在
            if ($return_type == 1) {
                echo 1;
            } else {
                return 1;
            }
        } else {
            //昵称可以使用
            if ($return_type == 1) {
                echo 2;
            } else {
                return 2;
            }
        }
    }

    //用户注册，写入数据
    function checkRegister() {
        $data['user_email'] = addslashes($_POST['user_email']);
        $data['user_nickname'] = addslashes($_POST['user_nickname']);
        $data['user_passwd'] = md5($_POST['user_passwd']);
        $data['user_gender'] = $_POST['user_gender'];
        $data['user_cdatetime'] = date("Y-m-d H:i:s");
        //验证邮箱是否可用
        $rule = '/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/';
        $user_email_return = $this->checkuseremail($data['user_email'], 2);
        if (!preg_match($rule, $data['user_email']) || $user_email_return == 1) {
            echo 1;
        } else {
            //验证昵称是否可用
            $rule = '/^[\x80-\xffA-Za-z0-9-_]*$/';
            $user_nickname_return = $this->checknickname($data['user_nickname'], 2);
            if (!preg_match($rule, $data['user_nickname']) || $user_nickname_return == 1) {
                echo 2;
            } else {
                //检验密码
                $rule = '/^(\w){6,20}$/';
                if (!preg_match($rule, $_POST['user_passwd'])) {
                    echo 3;
                } else {
                    //校验验证码
                    $auth = $_POST['auth'];
                    $auth_array = C('AUTH_ARRAY');
                    $key = $_SESSION['verify'];
                    if ($auth != $auth_array[$key]) {
                        echo 4;
                    } else {
                        $User = M('user_base_info');
                        if ($User->add($data)) {
                            require_once(LIB_PATH . 'ORG/String.class.php');
                            $email_key = base64_encode(String::rand_string(10));
                            $user_nickname = $data['user_nickname'];
                            $user_email = $data['user_email'];
                            session('user_email',$user_email); //session用户邮箱
                            session('user_nickname',$user_nickname); //session用户昵称
                            $link = C('WEB_URL') . '/index.php/Public/activation/user_email/' . $user_email . '/email_key/' . $email_key;
                            $email_content = $user_nickname . '，你好<br>请点此<a href="' . $link . '">' . $link . '</a>激活邮件。如点击不了，请复制以上链接粘贴在浏览器中打开。<br><br><br>24淘祝您购物愉快！<br>' . date("Y-m-d");
                            $this->sendEmail(1, array($user_email), '24淘（www.24tao.com）提醒您激活账号', $email_content, $email_key, 1);
                            echo 5;
                        } else {
                            echo 6;
                        }
                    }
                }
            }
        }
    }

    /**
     * 注册成功后，提示邮箱激活的页面
     */
    function activationpage() {
        $user_nickname = $_SESSION['user_nickname'];
        $user_email = $_SESSION['user_email'];
        if (empty($user_email) || empty($user_nickname)) {
            //跳转至登录页
            $this->redirect('Public/login');
        }
        $this->assign('title', '邮件激活 - ' . C('TITLE'));
        $this->assign('user_nickname', $user_nickname);
        $this->assign('user_email', $user_email);
        $this->display();
    }

    /**
     * 邮箱激活
     */
    function activation() {
        $user_email = addslashes($_GET['user_email']);
        $email_key = addslashes($_GET['email_key']);
        $User = M('user_base_info');
        //判断是否已经激活了，防止用户恶意点击激活链接
        $user_status = $User->where("user_email = '$user_email'")->getField('user_status');
        if ($user_status == 1) {
            //未激活，判断激活链接是否有效
            $Email = M('user_sendemail_list');
            $rows = $Email->where("user_email = '$user_email' and email_type = 1")->field('email_key')->order('create_datetime desc')->find();
            if ($rows['email_key'] != $email_key) {
                //此激活链接已失效
                $this->assign('link_status', 1);
            } else {
                //修改用户状态为已激活
                $data['user_status'] = 2;
                $User->where("user_email = '$user_email'")->save($data);
                $this->assign('link_status', 2);
                $this->assign('user_email', $user_email);
            }
        } else {
            $this->assign('link_status', 3);
        }
        $this->display();
    }

    /**
     * 再次下发激活邮件，十分钟一次，一天最多三次
     */
    function sendAgain() {
        $user_nickname = $_SESSION['user_nickname'];
        $user_email = $_SESSION['user_email'];
        $Email = M('user_sendemail_list');
        $email_info = $Email->where("user_email = '$user_email'")->order('create_datetime desc')->limit(1)->find();
        $enable_time = time() - 10 * 60;
        $today = date("Y-m-d");
        $send_email_count = $Email->where("user_email = '$user_email' and email_type = 1 and left(create_datetime,10) = '$today'")->count(); //这个邮箱发送注册验证邮件的个数
        if (strtotime($email_info['create_datetime']) > $enable_time) {
            echo '请十分钟后再次发送！';
        } elseif ($send_email_count >= 3) {
            echo '今日发送超限！';
        } else {
            //再次发送
            require_once(LIB_PATH . 'ORG/String.class.php');
            $email_key = base64_encode(String::rand_string(10));
            $link = C('WEB_URL') . '/index.php/Public/activation/user_email/' . $user_email . '/email_key/' . $email_key;
            $email_content = $user_nickname . '，你好<br>请点此<a href="' . $link . '">' . $link . '</a>激活邮件。如点击不了，请复制以上链接粘贴在浏览器中打开。<br><br><br>24淘祝您购物愉快！<br>' . date("Y-m-d");
            if ($this->sendEmail(1, array($user_email), '24淘（www.24tao.com）提醒您激活账号', $email_content, $email_key, 1)) {
                echo '邮件发送成功！';
            } else {
                echo '邮件下发失败！';
            }
        }
    }


    /**
     * 登陆中心页
     */
    function login() {
        //首先验证用户是否已登录，已登录的话直接跳转至首页
        if (!session(C('USER_AUTH_KEY'))) {
            $this->assign('title', '用户登录 - ' . C('TITLE'));
            $this->display();
        } else {
            $this->redirect('Index/index');
        }
    }

    /**
     * 用户登陆 - 验证
     */
    function checkLogin() {
        $user_email = addslashes($_POST['user_email']);
        $user_passwd = md5($_POST['user_passwd']);
        $autologin = $_POST['autologin'];
        $User = M('user_base_info');
        $rows = $User->where("user_email = '$user_email' and user_passwd = '$user_passwd'")->find();
        if (empty($rows)) {
            echo 1; //用户名或密码错误
        } elseif ($rows['user_status'] == 1) {
            echo 2; //账号未激活
        } elseif ($rows['user_status'] == 3) {
            echo 3; //账号已停用
        } else {
            if ($autologin == 1) {
                cookie('user_email', $user_email, time() + 2 * 7 * 24 * 60 * 60);
                cookie('user_passwd', $user_passwd, time() + 2 * 7 * 24 * 60 * 60);
            }
            //设置登陆信息
            session(C('USER_AUTH_KEY'), $rows['user_code']);
            session('user_email', $rows['user_email']);
            session('user_nickname', $rows['user_nickname']);
            session('user_province', $rows['user_province']);
            session('user_city', $rows['user_city']);
            session('user_industry', $rows['user_industry']);
            session('api_logo_add', $rows['api_logo_add']);
            session('user_logo_add', $rows['user_logo_add']);
            session('user_gender', $rows['user_gender']);
            session('user_birth_date', $rows['user_birth_date']);
            session('user_integral', $rows['user_integral']);
            //保存登陆记录（暂且不做）

            //计算连续登录天数（暂且不做）

            echo 4; //登陆成功
        }
    }

    //退出登陆
    function logout() {
        if (session(C('USER_AUTH_KEY'))) {
            session(null); //清空当前session
            session('[destroy]'); // 销毁session
            $this->redirect('Index/index');
        } else {
            $this->redirect('Index/index');
        }
    }

}

?>